/*
 * Copyright (c) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License,Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.huawei.cookbooks.slice;

import com.github.boxuanjia.toycar.ToyCar;
import com.huawei.cookbooks.ResourceTable;
import com.huawei.cookbooks.bean.BeautyInfo;
import com.huawei.cookbooks.utils.ComponentProviderUtils;
import com.huawei.cookbooks.utils.DateUtils;
import com.huawei.cookbooks.utils.JsonUtils;
import com.huawei.cookbooks.utils.LogUtils;
import com.ohosnetworking.error.ANError;
import com.ohosnetworking.interfaces.ParsedRequestListener;
import com.rx2ohosnetworking.Rx2OhosNetworking;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.agp.utils.Color;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;
import timber.log.Timber;

import java.util.*;

/**
 * Clock Card Slice
 */
public class ClockCardSlice extends AbilitySlice {
    private static final long SEND_PERIOD = 1000L;
    private static final int COLOR_RGB = 192;
    private static final int TIME_LENGTH = 2;
    private Text dateText;
    private Text hourText;
    private Text minText;
    private Text secondText;
    private EventRunner runner;
    private MyEventHandle myEventHandle;
    private AbilitySlice slice = this;
    private Timer timer;
    private List<BeautyInfo.ProfileInfo> profileInfo = new ArrayList<>();
    private ListContainer mListContainer;
    private Runnable runnable = new Runnable() {
        private void initHandler() {
                runner = EventRunner.getMainEventRunner();
                if (runner == null) {
                    return;
                }
                myEventHandle = new MyEventHandle(runner);
            }

            @Override
            public void run() {
                // 初始化认证对象
                initHandler();
            }
        };

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_slice_clock_card);
        initComponent();
        startTimer();

        mListContainer = (ListContainer) findComponentById(ResourceTable.Id_infoList);
        mListContainer.setItemProvider(new RecycleItemProvider() {

            @Override
            public int getCount() {
                return profileInfo.size();
            }

            @Override
            public BeautyInfo.ProfileInfo getItem(int i) {
                return profileInfo.get(i);
            }

            @Override
            public long getItemId(int i) {
                return i;
            }

            @Override
            public Component getComponent(int i, Component component, ComponentContainer componentContainer) {
                Timber.d("getComponent() called with: i = [ %s ], component = [ %s ], componentContainer = [ %s ]", i, component, componentContainer);
                if (component==null) {
                    DirectionalLayout line = (DirectionalLayout) LayoutScatter.getInstance(getContext())
                            .parse(ResourceTable.Layout_item_info, null, false);
                    Text title = (Text) line.findComponentById(ResourceTable.Id_title);
                    title.setText(getItem(i).getTitle());
                    Text note = (Text) line.findComponentById(ResourceTable.Id_note);
                    note.setText(getItem(i).getNote());
                    component = line;
                }

                return component;
            }
        });
    }

    @Override
    public void requestPermissionsFromUser(String[] permissions, int requestCode) {
        super.requestPermissionsFromUser(permissions, requestCode);
    }

    private void startTimer() {
        timer = new Timer();
        timer.schedule(
                new TimerTask() {
                    @Override
                    public void run() {
                        runnable.run();
                        myEventHandle.sendEvent(1);
                    }
                },
                0,
                SEND_PERIOD);
    }

    /**
     * Init Component
     */
    private void initComponent() {
        Timber.d("initComponent() called");
        Calendar now = Calendar.getInstance();
        int hour = now.get(Calendar.HOUR_OF_DAY);
        int min = now.get(Calendar.MINUTE);

        Component dateComponent = slice.findComponentById(ResourceTable.Id_date);
        if (dateComponent instanceof Text) {
            dateText = (Text) dateComponent;
            dateText.setText(DateUtils.getCurrentDate("yyyy-MM-dd"));
        }
        Component hourComponent = slice.findComponentById(ResourceTable.Id_hour);
        if (hourComponent instanceof Text) {
            hourText = (Text) hourComponent;
            setTextValue(hour, hourText);
        }
        Component minComponent = findComponentById(ResourceTable.Id_min);
        if (minComponent instanceof Text) {
            minText = (Text) minComponent;

            setTextValue(min, minText);
        }
        Component secComponent = findComponentById(ResourceTable.Id_sec);
        if (secComponent instanceof Text) {
            secondText = (Text) secComponent;
            int second = now.get(Calendar.SECOND);
            setTextValue(second, secondText);
        }
        int weekId = ComponentProviderUtils.getWeekDayId();
        Component weekComponent = slice.findComponentById(weekId);
        if (weekComponent instanceof Text) {
            Text week = (Text) weekComponent;
            week.setTextColor(new Color(Color.rgb(0, 0, 0)));
        }
        int lastWeekDayId = ComponentProviderUtils.getLastWeekDayId();
        Component lastWeekComponent = slice.findComponentById(lastWeekDayId);
        if (weekComponent != null && lastWeekComponent instanceof Text) {
            Text lastWeek = (Text) lastWeekComponent;
            lastWeek.setTextColor(new Color(Color.rgb(COLOR_RGB, COLOR_RGB, COLOR_RGB)));
        }

        String timeStr = ComponentProviderUtils.getTimeStr(hour, min);
        String imageUrl = ComponentProviderUtils.getImageUrl(timeStr);
        Image timeImage = (Image) slice.findComponentById(ResourceTable.Id_timeImage);
        ToyCar.load(imageUrl).into(timeImage);

        String infoUrl = ComponentProviderUtils.getInfoUrl(timeStr);
        Rx2OhosNetworking.get(infoUrl).setTag("info").build()
                .getAsObject(BeautyInfo.class, new ParsedRequestListener<BeautyInfo>() {
                    @Override
                    public void onResponse(BeautyInfo o) {

                        String s = JsonUtils.toJsonString(o);
                        LogUtils.info("onNext", s);
                        if (o.getSuccess()) {
                            profileInfo = o.getResult().getProfileInfo();

                            mListContainer.getItemProvider().notifyDataChanged();
                        }
                    }

                    @Override
                    public void onError(ANError anError) {

                        LogUtils.info("onError", anError.getMessage());
                    }
                });

    }

    private void setTextValue(int now, Text text) {
        if (String.valueOf(now).length() < TIME_LENGTH) {
            text.setText("0" + now);
        } else {
            text.setText(now + "");
        }
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    private class MyEventHandle extends EventHandler {
        MyEventHandle(EventRunner runner) throws IllegalArgumentException {
            super(runner);
        }

        @Override
        protected void processEvent(InnerEvent event) {
            super.processEvent(event);
            int eventId = event.eventId;
            if (eventId == 1) {
                // 更新页面
                initComponent();
            }
        }
    }

    @Override
    protected void onStop() {
        LogUtils.info("onStop", " start to destroy slice");
        timer.cancel();
    }
}
